package com.itheima.service.mongo;

import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Sound;
import com.itheima.domain.mongo.SoundTime;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


@Service
public class SoundServiceImpl implements SoundService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveSound(Sound sound) {
        mongoTemplate.save(sound);
    }

    @Override
    public Sound findSound() {
        /*//查询总量
        long count = mongoTemplate.count(new Query(), Sound.class);
        //生成随机数
        count = RandomUtil.randomLong(count);
        Query query = new Query().skip(count).limit(1);
        Sound sound = mongoTemplate.findOne(query, Sound.class);*/
        List<Sound> soundList = mongoTemplate.findAll(Sound.class);
        Sound sound = RandomUtil.randomEle(soundList);
        return sound;
    }

    @Override
    public SoundTime findSoundTime(Long userId) {
        Query query = new Query(
                Criteria.where("userId").is(userId)
        );
        SoundTime soundTime = mongoTemplate.findOne(query, SoundTime.class);
        return soundTime;
    }

    @Override
    public void deleteSound(Long likeUserId,String objectId) {
        Query query = new Query(
                Criteria.where("userId").is(likeUserId)
                .and("id").is(new ObjectId(objectId))
        );
        mongoTemplate.remove(query,Sound.class);
    }

    @Override
    public void saveSoundTime(SoundTime soundTime) {
        mongoTemplate.save(soundTime);
    }
}
